/*
 * etco2Handling.c
 *
 *  Created on: 13-09-2012
 *      Author: Mati
 */


#include "ApplicationTasks.h"

#define dCO2 1		//%

extern xSemaphoreHandle xEtco2Received;
extern xSemaphoreHandle xBreathParamsReceived;

void vETCO2Task(void *pvParameters){

	float co2_current = 0;
	float co2_previous = 0;
	float co2_max = 0;
	uint8_t IsBreathNew = 0;
	vSemaphoreCreateBinary( xEtco2Received );
	vSemaphoreCreateBinary( xBreathParamsReceived );
	//printf("ETCO2 Task\n\r");


/*
#ifdef	INCLUDE_uxTaskGetStackHighWaterMark == 1
	unsigned portBASE_TYPE uxHighWaterMark;
    // Inspect our own high water mark on entering the task.
	uxHighWaterMark = uxTaskGetStackHighWaterMark( NULL );
	printf("ETCO2 Task Stack: %d\n\r", uxHighWaterMark);
#endif
*/


	xSemaphoreTake( xEtco2Received, 0 ); //pominiecie 1 odczytu
	xSemaphoreTake( xBreathParamsReceived, 0 ); //pominiecie 1 odczytu

    LPC_UART2->IER = (1<<0);	//RBR Interrupt enabled (Receive Buffer)
    NVIC_EnableIRQ(UART2_IRQn);
    NVIC_SetPriority(UART2_IRQn, 1);

	while(1){
			if ( xEtco2Received != NULL ){
				if ( pdTRUE == xSemaphoreTake( xEtco2Received, (portTickType) portMAX_DELAY))
				{
						co2_previous = co2_current;
						co2_current = GetCO2Concentration();
						//printf("%2.3f\n\r", co2_current);
						if(1 == IsBreathNew && (((co2_current - co2_previous)/co2_current)*100 < dCO2) && co2_current > 25)
						{
							//w tym miejscu następuje uruchomienie zaworów
							//zatrzymujących próbkę oddechu
							vSetSpeakerParams(10, 1000);
							IsBreathNew = 0;
						}
						if(co2_current < 1)
						{
							IsBreathNew = 1;
						}

/*
				#ifdef	INCLUDE_uxTaskGetStackHighWaterMark == 1
				// Calling the function will have used some stack space, we would
				// therefore now expect uxTaskGetStackHighWaterMark() to return a
				// value lower than when it was called on entering the task.
					uxHighWaterMark = uxTaskGetStackHighWaterMark( NULL );
					printf("ETCO2 Task Stack: %d\n\r", uxHighWaterMark);
				#endif
*/

				}
				//if ( pdTRUE == xSemaphoreTake( xBreathParamsReceived, (portTickType) portMAX_DELAY))
				//{
					//obsluga odczytanych parametrow z ETCO2
				//}
			}
	}
}
